package cn.oi.klittle.era.activity.edit

import android.os.Bundle
import android.view.View
import cn.oi.klittle.era.base.KBaseActivity
import cn.oi.klittle.era.comm.kpx


/**
 * fixme 文本编辑器
 */
open class KEditActivity : KBaseActivity() {

    override fun isEnableSliding(): Boolean {
        return true
    }

    override fun shadowSlidingWidth(): Int {
        //return super.shadowSlidingWidth()
        return kpx.screenWidth() / 2
    }

    override fun isDark(): Boolean {
        return true
    }

    var ui: KEditUi? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        try {
            super.onCreate(savedInstanceState)
            ui = KEditUi()
            setContentView(ui?.createView(this))
            initEvent()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object {
        var textMaxLength = 300//最大文本长度
        var textContent: String? = null//文本内容
        var textCallBack: ((content: String?) -> Unit)? = null

        //文本内容编辑回调。
        fun onTextCallBack(textCallBack: ((content: String?) -> Unit)? = null) {
            this.textCallBack = textCallBack
        }
    }

    fun initEvent() {
        setSoftInputMode_adjustpan_visible()
        onGlobalLayoutListener(isAlways = false) {
            ui?.edit?.let {
                it.requestFocus()//聚焦自动弹出软键盘。
            }
        }
        ui?.edit?.setText(textContent)//文本内容
        if (textMaxLength <= 0) {
            ui?.txt?.visibility = View.INVISIBLE//fixme 小于等于0，不显示文本长度。
        } else {
            ui?.txt?.visibility = View.VISIBLE
            ui?.edit?.setMaxLength(textMaxLength)//文本最大长度。
            ui?.txt?.setText(ui?.edit?.text?.length.toString() + "/" + textMaxLength.toString())
            ui?.edit?.addTextWatcher {
                ui?.txt?.setText(it.length.toString() + "/" + textMaxLength.toString())
            }
        }
        //保存按钮
        ui?.toolbar?.rightTextView?.onClick {
            var text = ui?.edit?.text?.toString()?.trim()//fixme 去除两端空格。
            textCallBack?.let { it(text) }
            textCallBack = null
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun finish() {
        try {
            super.finish()
            ui?.destroy(this)//界面销毁
            textCallBack = null
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

}